
<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <!-- 默认显示的查询条件 -->
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="searchInfo.deviceCode" placeholder="请输入设备编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="searchInfo.deviceName" placeholder="请输入设备名称" clearable />
            </el-form-item>
          </el-col>
<!--          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所在位置" prop="location">
              <el-input v-model="searchInfo.location" placeholder="请输入所在位置" clearable />
            </el-form-item>
          </el-col>-->
        </el-row>

        <!-- 展开后显示的额外查询条件 -->
        <template v-if="showAllQuery">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="运营状态" prop="operateStatus">
                <el-select v-model="searchInfo.operateStatus" placeholder="请选择运营状态" clearable>
                  <el-option v-for="item in operateStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="运行状态" prop="runStatus">
                <el-select v-model="searchInfo.runStatus" placeholder="请选择运行状态" clearable>
                  <el-option v-for="item in runStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="激活状态" prop="activateStatus">
                <el-select v-model="searchInfo.activateStatus" placeholder="请选择激活状态" clearable>
                  <el-option v-for="item in activateStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
<!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="售后人员" prop="afterSalesPerson">
                <el-input v-model="searchInfo.afterSalesPerson" placeholder="请输入售后人员" clearable />
              </el-form-item>
            </el-col>-->
          </el-row>
        </template>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery=true" v-if="!showAllQuery">更多条件</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery=false" v-else>收起条件</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button  type="primary" icon="plus" @click="openDialog()">新增</el-button>
        <el-button  icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>
        <ExportTemplate  template-id="device_Devices" />
        <ExportExcel  template-id="device_Devices" filterDeleted/>
        <ImportExcel  template-id="device_Devices" @on-success="getTableData" />
      </div>
      <el-table
          ref="multipleTable"
          style="width: 100%"
          tooltip-effect="dark"
          :data="tableData"
          row-key="id"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column align="left" label="设备编号" prop="deviceCode" width="120" />

        <el-table-column align="left" label="设备名称" prop="deviceName" width="120" />

        <el-table-column align="left" label="所在位置" prop="location" width="120" />

        <el-table-column align="left" label="运营状态" prop="operateStatus" width="120">
          <template #default="scope">
            {{ filterDict(scope.row.operateStatus,operateStatusOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="运行状态" prop="runStatus" width="120">
          <template #default="scope">
            {{ filterDict(scope.row.runStatus,runStatusOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="激活状态" prop="activateStatus" width="120">
          <template #default="scope">
            {{ filterDict(scope.row.activateStatus,activateStatusOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="软件版本" prop="softwareVersion" width="120" />

        <el-table-column align="left" label="售后人员" prop="afterSalesPerson" width="120" />

        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
          <template #default="scope">
            <el-button  type="primary" link class="table-button" @click="getDetails(scope.row)"><el-icon style="margin-right: 5px"><InfoFilled /></el-icon>查看</el-button>
            <el-button  type="primary" link icon="edit" class="table-button" @click="updateDevicesFunc(scope.row)">编辑</el-button>
            <el-button   type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{type==='create'?'新增':'编辑'}}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">

        <el-form-item label="设备编号:" prop="deviceCode">
          <el-input v-model="formData.deviceCode" placeholder="请输入设备编号" clearable />
          <div class="form-tip">设备唯一标识码，不可重复</div>
        </el-form-item>
        <el-form-item label="设备名称:" prop="deviceName">
          <el-input v-model="formData.deviceName" :clearable="true" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="所在位置:" prop="location">
          <el-input v-model="formData.location" :clearable="true" placeholder="请输入所在位置" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="运营状态:" prop="operateStatus">
              <el-select v-model="formData.operateStatus" placeholder="请选择运营状态" style="width:100%" clearable>
                <el-option v-for="(item,key) in operateStatusOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运行状态:" prop="runStatus">
              <el-select v-model="formData.runStatus" placeholder="请选择运行状态" style="width:100%" clearable>
                <el-option v-for="(item,key) in runStatusOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="激活状态:" prop="activateStatus">
              <el-select v-model="formData.activateStatus" placeholder="请选择激活状态" style="width:100%" clearable>
                <el-option v-for="(item,key) in activateStatusOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="软件版本:" prop="softwareVersion">
          <el-input v-model="formData.softwareVersion" :clearable="true" placeholder="请输入软件版本" />
        </el-form-item>
        <el-form-item label="售后人员:" prop="afterSalesPerson">
          <el-input v-model="formData.afterSalesPerson" placeholder="请输入售后人员" clearable />
          <div class="form-tip">负责此设备的售后工程师姓名</div>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true" :before-close="closeDetailShow" title="查看">
      <el-descriptions :column="1" border>

        <el-descriptions-item label="设备编号">
          {{ detailFrom.deviceCode }}
        </el-descriptions-item>
        <el-descriptions-item label="设备名称">
          {{ detailFrom.deviceName }}
        </el-descriptions-item>
        <el-descriptions-item label="所在位置">
          {{ detailFrom.location }}
        </el-descriptions-item>
        <el-descriptions-item label="运营状态">
          {{ detailFrom.operateStatus }}
        </el-descriptions-item>
        <el-descriptions-item label="运行状态">
          {{ detailFrom.runStatus }}
        </el-descriptions-item>

        <el-descriptions-item label="激活状态">
          {{ detailFrom.activateStatus }}
        </el-descriptions-item>

        <el-descriptions-item label="软件版本">
          {{ detailFrom.softwareVersion }}
        </el-descriptions-item>
        <el-descriptions-item label="售后人员">
          {{ detailFrom.afterSalesPerson }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>

  </div>
</template>

<script setup>
import {
  createDevices,
  deleteDevices,
  deleteDevicesByIds,
  updateDevices,
  findDevices,
  getDevicesList
} from '@/api/device/devices'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict ,filterDataSource, returnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useAppStore } from "@/pinia"

// 导出组件
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
// 导入组件
import ImportExcel from '@/components/exportExcel/importExcel.vue'
// 导出模板组件
import ExportTemplate from '@/components/exportExcel/exportTemplate.vue'

defineOptions({
  name: 'Devices'
})

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()

// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 自动化生成的字典（可能为空）以及字段
const operateStatusOptions = ref([])
const runStatusOptions = ref([])
const presenceOptions = ref([])
const activateStatusOptions = ref([])
const softwareStatusOptions = ref([])
const formData = ref({
  id: undefined,
  createdAt: new Date(),
  updatedAt: new Date(),
  deletedAt: new Date(),
  deviceCode: '',
  deviceName: '',
  location: '',
  operateStatus: '',
  runStatus: '',
  presence: '',
  activateStatus: '',
  softwareStatus: '',
  softwareVersion: '',
  afterSalesPerson: '',
})

// 验证规则
const rule = reactive({
  deviceCode: [
    { required: true, message: '设备编号不能为空', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  deviceName: [
    { required: true, message: '设备名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '所在位置不能为空', trigger: 'blur' },
    { max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ],
  operateStatus: [
    { required: true, message: '请选择运营状态', trigger: 'change' }
  ],
  runStatus: [
    { required: true, message: '请选择运行状态', trigger: 'change' }
  ],
  activateStatus: [
    { required: true, message: '请选择激活状态', trigger: 'change' }
  ],
  softwareVersion: [
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  afterSalesPerson: [
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ]
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
/*const getTableData = async() => {
  const table = await getDevicesList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}*/
const getTableData = async() => {
  try {
    getDevicesList.value = true
    const table = await getDevicesList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchInfo.value
    })

    if (table.code === 0) {
      tableData.value = table.data.list
      total.value = table.data.total
      page.value = table.data.page
      pageSize.value = table.data.pageSize
    }
  } catch (error) {
    console.error("获取设备列表失败:", error)
    ElMessage.error("获取设备列表失败，请稍后重试")
  } finally {
    getDevicesList.value = false
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
  operateStatusOptions.value = await getDictFunc('operateStatus')
  runStatusOptions.value = await getDictFunc('runStatus')
  presenceOptions.value = await getDictFunc('presence')
  activateStatusOptions.value = await getDictFunc('activateStatus')
  softwareStatusOptions.value = await getDictFunc('softwareStatus')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDevicesFunc(row)
  })
}

// 多选删除
const onDelete = async() => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    const ids = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
    multipleSelection.value.map(item => {
      ids.push(item.id)
    })
    const res = await deleteDevicesByIds({ ids })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === ids.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateDevicesFunc = async(row) => {
  const res = await findDevices({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteDevicesFunc = async (row) => {
  const res = await deleteDevices({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    id: undefined,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: new Date(),
    deviceCode: '',
    deviceName: '',
    location: '',
    operateStatus: '',
    runStatus: '',
    presence: '',
    activateStatus: '',
    softwareStatus: '',
    softwareVersion: '',
    afterSalesPerson: '',
  }
}
// 弹窗确定
const enterDialog = async () => {
  btnLoading.value = true
  elFormRef.value?.validate( async (valid) => {
    if (!valid) return btnLoading.value = false
    let res
    switch (type.value) {
      case 'create':
        res = await createDevices(formData.value)
        break
      case 'update':
        res = await updateDevices(formData.value)
        break
      default:
        res = await createDevices(formData.value)
        break
    }
    btnLoading.value = false
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const detailFrom = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findDevices({ ID: row.ID })
  if (res.code === 0) {
    detailFrom.value = res.data
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailFrom.value = {}
}


</script>

<style scoped>
.gva-search-box {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.gva-btn-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 15px;
}

.gva-table-box {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-container {
  padding: 0 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.detail-container {
  padding: 20px;
}

.detail-value {
  font-weight: 500;
  color: #333;
}

.detail-footer {
  margin-top: 20px;
  text-align: center;
}

.gva-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-tag {
  margin: 0 2px;
}
</style>